import typer
import sys

sys.path.append("../")  # noqa
from config import client, col_register, col_activity, col_alumni, col_institution

app = typer.Typer()


@app.command(name="clean-refs")
def check_orphan():
    """移除无效的报名refs_person_ids和活动"""

    contacts = col_register.find({"is_attended": True}).distinct("person_id")
    persons = col_alumni.find({"is_deleted": {"$ne": True}}).distinct("_id")
    delete_ids = set(contacts) - set(persons)
    col_register.delete_many({"person_id": {"$in": list(delete_ids)}})

    #  处理活动
    activity_ids = col_register.find({"is_attended": True}).distinct("activity_id")
    act = col_activity.find({"is_deleted": {"$ne": True}}).distinct("_id")
    delete_ids = set(activity_ids) - set(act)
    col_register.delete_many({"activity_id": {"$in": list(delete_ids)}})
    print("end...")


if __name__ == "__main__":
    app()
